package com.sparrow.rpc.socket.codec;

import com.sparrow.rpc.socket.msg.RpcCodecMsg;
import com.sparrow.rpc.socket.msg.RpcMsgType;
import com.sparrow.rpc.socket.msg.req.RpcLoginRequest;
import com.sparrow.rpc.socket.msg.req.RpcRequest;
import com.sparrow.rpc.socket.msg.resp.RpcLoginResponse;
import com.sparrow.rpc.socket.msg.resp.RpcNodeBroadcastResponse;
import com.sparrow.rpc.socket.msg.resp.RpcResponse;
import com.sparrow.rpc.util.RpcUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public class RpcDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) {
        // 读取消息类型
        byte msgType = byteBuf.readByte();
        // 读取消息长度
        int len = byteBuf.readInt();
        if (byteBuf.readableBytes() < len) {
            throw new IllegalArgumentException("消息长度异常: " + len);
        }
        // 选择合适的类进行反序列化
        Class<?> clazz = RpcMsgType.getMsgClass(msgType);
        if (clazz == null) {
            throw new IllegalArgumentException("未知的消息类型: " + msgType);
        }
        // 读取消息体
        byte[] bytes = new byte[len];
        byteBuf.readBytes(bytes);

        // 反序列化
        Object msg = RpcUtil.getSerializer().deserialize(bytes, clazz);
        if (msg != null) {
            out.add(msg);
        } else {
            throw new RuntimeException("反序列化失败，数据为空");
        }
    }

}
